/**
 * 自动语音导览组件
 *
 * 功能：
 * 1. 进入页面自动播报当前位置
 * 2. 询问用户是否需要讲解
 * 3. 识别用户回答（需要/不需要）
 * 4. 根据回答开始讲解或退出
 */

import React, { useState, useEffect, useRef } from 'react';
import {
  Modal,
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Animated,
  Dimensions,
  PermissionsAndroid,
  Platform,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import voiceService from '../services/voiceService';
import { analyzeIntent } from '../utils/voiceKeywords';

const { width } = Dimensions.get('window');

const AutoVoiceGuide = React.memo(({
  visible,
  onClose,
  scenicArea,
  currentLocation,
  navigation, // 导航对象
  autoStart = true, // 是否自动开始
  autoStartDelay = 1000, // 自动开始延迟（毫秒）
}) => {
  const [status, setStatus] = useState('idle'); // idle, asking, listening, speaking, recognizing, guiding, completed, error, confirm
  const [recognizedText, setRecognizedText] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [hasStarted, setHasStarted] = useState(false);
  const [showConfirmButtons, setShowConfirmButtons] = useState(false); // 显示确认按钮

  const pulseAnim = useRef(new Animated.Value(1)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;

  // 当前弹窗是否仍然有效（用于在关闭后阻止后续异步回调继续执行）
  const isActiveRef = useRef(false);

  // 请求麦克风权限
  const requestMicrophonePermission = async () => {
    if (Platform.OS === 'ios') {
      return true; // iOS 权限在 Info.plist 中配置
    }

    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
        {
          title: '麦克风权限',
          message: '需要使用麦克风进行语音识别和语音交互',
          buttonPositive: '允许',
          buttonNegative: '拒绝',
        },
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (error) {
      return false;
    }
  };

  // 生成欢迎语
  const generateWelcomeMessage = () => {
    // 确保使用最新的位置信息
    const locationName =
      currentLocation?.name ||
      scenicArea?.areaName ||
      scenicArea?.name ||
      '当前位置';

    return `您好，您现在的位置是${locationName}，是否需要为您讲解？`;
  };

  // 初始化并自动开始语音导览（增强版）
  const initializeAutoGuide = async () => {
    // 弹窗已被关闭时不再执行任何逻辑
    if (!isActiveRef.current) return;
    if (hasStarted) return;

    try {
      setHasStarted(true);
      setStatus('asking');

      // 请求麦克风权限
      const hasPermission = await requestMicrophonePermission();
      if (!isActiveRef.current) return;
      if (!hasPermission) {
        // 用户拒绝权限，直接关闭弹窗，不播报任何内容
        onClose();
        return;
      }

      // 增加延迟时间，确保位置信息已经更新到最新值
      // 这样可以避免播报旧的位置信息
      await new Promise(resolve => setTimeout(resolve, 500)); // 从100ms增加到500ms
      if (!isActiveRef.current) return;

      // 播放欢迎语并询问（使用最新的位置信息）
      // 在播报前重新生成欢迎语，确保使用最新的scenicArea和currentLocation
      const welcomeText = generateWelcomeMessage();
      if (!isActiveRef.current) return;

      setStatus('speaking');
      await voiceService.speak(welcomeText);
      if (!isActiveRef.current) return;

      // 等待音频系统切换（优化延迟时间）
      await new Promise(resolve => setTimeout(resolve, 50));
      if (!isActiveRef.current) return;

      // 开始监听用户回答
      startListening();
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('语音服务初始化失败：' + (error.message || '未知错误'));
      setStatus('error');
    }
  };

  // 生成讲解内容
  const generateGuideContent = () => {
    if (!scenicArea) {
      return '很抱歉，暂时没有该景区的详细介绍。';
    }

    const {
      areaName,
      name,
      address,
      rating,
      level,
      introduction,
      description,
    } = scenicArea;
    const displayName = areaName || name || '本景区';

    let content = `好的，现在为您介绍${displayName}。`;

    if (level) {
      content += `这是一个${level}景区。`;
    }

    if (rating) {
      content += `游客评分${rating}分。`;
    }

    if (address) {
      content += `位于${address}。`;
    }

    // 添加详细介绍
    if (introduction) {
      content += introduction;
    } else if (description) {
      content += description;
    } else {
      content += '这里风景优美，是旅游观光的好去处。';
    }

    return content;
  };



  // 开始监听用户语音
  const startListening = async () => {
    if (!isActiveRef.current) return;

    try {
      setStatus('listening');
      setRecognizedText('');

      let hasProcessed = false; // 防止重复处理
      let listeningTimer = null; // 15秒超时计时器

      // 🕐 设置15秒超时 - 超时后显示确认按钮（优化体验）
      listeningTimer = setTimeout(async () => {
        if (!isActiveRef.current) return;
        if (!hasProcessed) {
          hasProcessed = true;

          await voiceService.stopListening();
          if (!isActiveRef.current) return;
          setStatus('confirm');
          setShowConfirmButtons(true);
          await voiceService.speak(
            '抱歉，我没听清楚。您可以点击屏幕上的"需要"或"不需要"按钮',
          );
        }
      }, 15000); // 15秒（从30秒优化）

      await voiceService.startListening({
        onStart: () => {
          if (!isActiveRef.current) return;
        },
        onResults: (text, { isFinal } = { isFinal: false }) => {
          if (!isActiveRef.current) return;
          if (!text || !text.trim()) {
            return;
          }

          // 不再显示识别文本给用户
          // setRecognizedText(text);

          // ✨ 实时判断意图，识别到关键词立即停止
          if (!hasProcessed) {
            const result = analyzeIntent(text);

            // 只要识别到明确的肯定或否定意图，立即停止
            if (result.intent === 'positive' || result.intent === 'negative') {
              hasProcessed = true;

              // 清除超时计时器
              if (listeningTimer) {
                clearTimeout(listeningTimer);
                listeningTimer = null;
              }

              if (isActiveRef.current) {
                handleRecognitionResult(text);
              }
            }
          }

          // 如果是最终结果且还未处理，则先判断意图
          if (isFinal && !hasProcessed) {
            const result = analyzeIntent(text);

            // 只有明确意图时才标记为已处理并清除计时器
            if (result.intent === 'positive' || result.intent === 'negative') {
              hasProcessed = true;

              // 清除超时计时器
              if (listeningTimer) {
                clearTimeout(listeningTimer);
                listeningTimer = null;
              }

              if (isActiveRef.current) {
                handleRecognitionResult(text);
              }
            } else {
              // unknown意图，不处理，继续监听等待15秒超时
            }
          }
        },
        onError: error => {
          // 清除超时计时器
          if (listeningTimer) {
            clearTimeout(listeningTimer);
            listeningTimer = null;
          }
          if (!isActiveRef.current) return;

          setErrorMessage(error.message || '语音识别失败');
          setStatus('error');
        },
        onEnd: () => {
          // 清除超时计时器
          if (listeningTimer) {
            clearTimeout(listeningTimer);
            listeningTimer = null;
          }
        },
      });
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('启动录音失败：' + error.message);
      setStatus('error');
    }
  };

  // 处理识别结果
  const handleRecognitionResult = async text => {
    if (!isActiveRef.current) return;

    try {
      // 分析用户意图
      const result = analyzeIntent(text);

      // 确保已停止监听（防御性编程）
      if (result.intent === 'positive' || result.intent === 'negative') {
        await voiceService.stopListening();
        if (!isActiveRef.current) return;
        setStatus('processing');
      }

      if (result.intent === 'positive') {
        // 用户想听讲解 - 直接跳转到景区详情页

        setStatus('speaking');
        await voiceService.speak('好的，为您打开景区详情');
        if (!isActiveRef.current) return;

        // 执行跳转
        if (navigation && scenicArea) {
          const itemData = scenicArea.raw || scenicArea;
          const areaType = itemData.areaType || 1;

          try {
            // 先清理资源
            await cleanup();

            if (isActiveRef.current) {
              navigation.navigate('AttractionDetail', {
                attraction: itemData,
                itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
                itemId: scenicArea.id,
                areaType: areaType,
              });
            }
          } catch (navError) {
            // 静默处理导航错误
          }
        } else {
          // navigation或scenicArea不存在
        }

        // 立即关闭弹窗
        onClose();
      } else if (result.intent === 'negative') {
        // 用户不想听，立即关闭弹窗
        await cleanup();
        onClose();
      } else {
        // 无法判断意图 - 不立即显示按钮，继续监听
        // 等待15秒超时后，由超时逻辑来显示按钮
        setStatus('listening');
      }
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('处理失败：' + error.message);
      setStatus('error');
    }
  };

  // 处理确认按钮点击 - 需要
  const handleConfirmYes = async () => {
    if (!isActiveRef.current) return;

    setShowConfirmButtons(false);
    setStatus('speaking');

    try {
      await voiceService.speak('好的，为您打开景区详情');
      if (!isActiveRef.current) return;

      // 跳转到景区详情页
      if (navigation && scenicArea) {
        const itemData = scenicArea.raw || scenicArea;
        const areaType = itemData.areaType || 1;

        // 先清理资源
        await cleanup();

        if (isActiveRef.current) {
          navigation.navigate('AttractionDetail', {
            attraction: itemData,
            itemType: areaType === 1 ? 'scenicArea' : 'scenicSpot',
            itemId: scenicArea.id,
            areaType: areaType,
          });
        }
      }

      setStatus('completed');
      // 立即关闭
      onClose();
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('跳转失败');
      setStatus('error');
    }
  };

  // 处理确认按钮点击 - 不需要
  const handleConfirmNo = async () => {
    if (!isActiveRef.current) return;

    setShowConfirmButtons(false);
    // 立即清理资源并关闭
    await cleanup();
    onClose();
  };

  // 播放景区讲解
  const playGuideContent = async () => {
    if (!isActiveRef.current) return;

    try {
      setStatus('guiding');
      const content = generateGuideContent();

      await voiceService.speak(content);
      if (!isActiveRef.current) return;

      setStatus('completed');
      // 先清理资源
      await cleanup();

      // 讲解完成后自动关闭
      setTimeout(() => {
        if (!isActiveRef.current) return;
        onClose();
      }, 2000);
    } catch (error) {
      if (!isActiveRef.current) return;
      setErrorMessage('播放讲解失败');
      setStatus('error');
      // 确保清理资源
      await cleanup();
    }
  };

  // 手动重新开始
  const handleRestart = async () => {
    if (!isActiveRef.current) return;

    // 先清理所有资源
    await cleanup();
    setHasStarted(false);
    setErrorMessage('');
    setRecognizedText('');
    setStatus('idle');
    // 重启时重新标记为激活状态
    isActiveRef.current = true;
    setTimeout(() => {
      if (!isActiveRef.current) return;
      initializeAutoGuide();
    }, 300);
  };

  // 清理资源 - 只清理 TTS，不影响音频播放
  const cleanup = async () => {
    // 标记为无效，后续异步回调直接退出
    isActiveRef.current = false;
    try {
      // 立即停止语音识别
      await voiceService.stopListening();
      // 立即停止语音播报
      await voiceService.stopSpeaking();
      // 清理TTS资源
      await voiceService.cleanupTts();
      setHasStarted(false);
      setStatus('idle');
      setRecognizedText('');
      setErrorMessage('');
    } catch (error) {
      // 忽略清理错误
    }
  };

  // 监听弹窗显示/隐藏
  useEffect(() => {
    if (visible && autoStart && !hasStarted) {
      // 弹窗显示时标记为激活
      isActiveRef.current = true;
      // 延迟启动，让用户有准备时间
      // 注意：initializeAutoGuide内部会延迟100ms确保位置信息已更新
      const timer = setTimeout(() => {
        if (!isActiveRef.current) return;
        initializeAutoGuide();
      }, autoStartDelay);

      return () => {
        clearTimeout(timer);
      };
    } else if (!visible) {
      // 弹窗被关闭，立即标记无效并清理
      isActiveRef.current = false;
      cleanup();
    }
  }, [visible, autoStart]);

  // 监听景区数据变化，确保只播报最新的景区名称
  useEffect(() => {
    if (visible && status === 'speaking' && hasStarted) {
      // 如果正在播报但景区数据已更新，确保使用最新数据
      // 注意：这里不立即中断播报，因为会影响用户体验
      // 而是在下次需要时使用最新数据
    }
  }, [scenicArea, currentLocation, visible, status, hasStarted]);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      isActiveRef.current = false;
      cleanup();
    };
  }, []);

  // 脉搏动画（录音时）
  useEffect(() => {
    if (status === 'listening') {
      Animated.loop(
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 1.2,
            duration: 800,
            useNativeDriver: true,
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 800,
            useNativeDriver: true,
          }),
        ]),
      ).start();
    } else {
      pulseAnim.setValue(1);
    }
  }, [status]);

  // 淡入动画
  useEffect(() => {
    if (visible) {
      Animated.timing(opacityAnim, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }).start();
    } else {
      opacityAnim.setValue(0);
    }
  }, [visible]);

  // 获取状态文本
  const getStatusText = () => {
    switch (status) {
      case 'idle':
        return '准备中...';
      case 'asking':
        return '正在询问...';
      case 'listening':
        return '请说出您的回答';
      case 'speaking':
        return '正在播放...';
      case 'recognizing':
        return '正在识别...';
      case 'confirm':
        return '请选择';
      case 'guiding':
        return '正在讲解...';
      case 'completed':
        return '完成';
      case 'error':
        return '出错了';
      default:
        return '';
    }
  };

  // 获取状态图标
  const getStatusIcon = () => {
    switch (status) {
      case 'idle':
      case 'asking':
      case 'speaking':
      case 'guiding':
        return 'volume-high';
      case 'listening':
        return 'mic';
      case 'recognizing':
        return 'search';
      case 'completed':
        return 'checkmark-circle';
      case 'error':
        return 'alert-circle';
      default:
        return 'help-circle';
    }
  };

  // 获取状态颜色
  const getStatusColor = () => {
    switch (status) {
      case 'error':
        return '#FF3B30';
      case 'completed':
        return '#34C759';
      case 'listening':
        return '#007AFF';
      case 'guiding':
        return '#5856D6';
      default:
        return '#5856D6';
    }
  };

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
      onRequestClose={onClose}
    >
      <Animated.View style={[styles.container, { opacity: opacityAnim }]}>
        <View style={styles.backdrop}>
          <View style={styles.content}>
            {/* 状态图标 */}
            <Animated.View
              style={[
                styles.iconContainer,
                {
                  backgroundColor: getStatusColor(),
                  transform: [{ scale: pulseAnim }],
                },
              ]}
            >
              <Icon name={getStatusIcon()} size={60} color="#FFFFFF" />
            </Animated.View>

            {/* 状态文本 */}
            <Text style={styles.statusText}>{getStatusText()}</Text>

            {/* 位置信息 */}
            {(status === 'asking' || status === 'speaking') && scenicArea && (
              <View style={styles.locationContainer}>
                <Icon name="location" size={20} color="#007AFF" />
                <Text style={styles.locationText}>
                  {scenicArea.areaName || scenicArea.name}
                </Text>
              </View>
            )}

            {/* 不再显示识别文本 */}

            {/* 确认按钮 */}
            {showConfirmButtons && (
              <View style={styles.confirmButtonsContainer}>
                <TouchableOpacity
                  style={[styles.confirmButton, styles.confirmYesButton]}
                  onPress={handleConfirmYes}
                  activeOpacity={0.8}
                >
                  <Icon name="checkmark-circle" size={24} color="#FFFFFF" />
                  <Text style={styles.confirmButtonText}>需要</Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={[styles.confirmButton, styles.confirmNoButton]}
                  onPress={handleConfirmNo}
                  activeOpacity={0.8}
                >
                  <Icon name="close-circle" size={24} color="#FFFFFF" />
                  <Text style={styles.confirmButtonText}>不需要</Text>
                </TouchableOpacity>
              </View>
            )}

            {/* 错误信息 */}
            {errorMessage ? (
              <View style={styles.errorContainer}>
                <Icon name="alert-circle" size={20} color="#FF3B30" />
                <Text style={styles.errorText}>{errorMessage}</Text>
              </View>
            ) : null}

            {/* 加载指示器 */}
            {(status === 'idle' ||
              status === 'asking' ||
              status === 'recognizing') && (
                <ActivityIndicator
                  size="large"
                  color={getStatusColor()}
                  style={styles.loader}
                />
              )}

            {/* 提示文本 */}
            {status === 'listening' && (
              <Text style={styles.hintText}>
                说"需要"开始讲解{'\n'}说"不需要"退出
              </Text>
            )}

            {/* 按钮组 */}
            <View style={styles.buttonContainer}>
              {/* 错误时显示重试按钮 */}
              {status === 'error' && (
                <TouchableOpacity
                  style={[styles.button, styles.retryButton]}
                  onPress={handleRestart}
                  activeOpacity={0.7}
                >
                  <Icon name="refresh" size={20} color="#FFFFFF" />
                  <Text style={styles.buttonText}>重试</Text>
                </TouchableOpacity>
              )}

              {/* 关闭按钮 */}
              <TouchableOpacity
                style={[styles.button, styles.closeButton]}
                onPress={async () => {
                  // 立即停止所有语音服务
                  await cleanup();
                  // 立即关闭弹窗
                  onClose();
                }}
                activeOpacity={0.7}
              >
                <Text style={styles.buttonText}>关闭</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Animated.View>
    </Modal>
  );
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backdrop: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    width: width * 0.85,
    backgroundColor: '#FFFFFF',
    borderRadius: 20,
    padding: 30,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 10,
    elevation: 5,
  },
  iconContainer: {
    width: 120,
    height: 120,
    borderRadius: 60,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 20,
  },
  statusText: {
    fontSize: 20,
    fontWeight: '600',
    color: '#333333',
    marginBottom: 15,
  },
  locationContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F0F8FF',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 8,
    marginBottom: 15,
  },
  locationText: {
    fontSize: 16,
    color: '#007AFF',
    marginLeft: 6,
    fontWeight: '500',
  },
  confirmButtonsContainer: {
    flexDirection: 'row',
    gap: 15,
    marginTop: 20,
    width: '100%',
  },
  confirmButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 16,
    borderRadius: 12,
    gap: 8,
  },
  confirmYesButton: {
    backgroundColor: '#34C759',
  },
  confirmNoButton: {
    backgroundColor: '#FF3B30',
  },
  confirmButtonText: {
    fontSize: 18,
    fontWeight: '600',
    color: '#FFFFFF',
  },
  recognizedContainer: {
    width: '100%',
    backgroundColor: '#F5F5F5',
    borderRadius: 10,
    padding: 15,
    marginTop: 10,
  },
  recognizedLabel: {
    fontSize: 14,
    color: '#666666',
    marginBottom: 5,
  },
  recognizedText: {
    fontSize: 16,
    color: '#333333',
    lineHeight: 24,
    fontWeight: '500',
  },
  errorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFEBEE',
    borderRadius: 10,
    padding: 15,
    marginTop: 10,
    width: '100%',
  },
  errorText: {
    fontSize: 14,
    color: '#FF3B30',
    marginLeft: 10,
    flex: 1,
  },
  loader: {
    marginTop: 15,
  },
  hintText: {
    fontSize: 14,
    color: '#666666',
    textAlign: 'center',
    marginTop: 10,
    lineHeight: 22,
  },
  buttonContainer: {
    flexDirection: 'row',
    marginTop: 20,
    gap: 10,
  },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 25,
    minWidth: 100,
  },
  retryButton: {
    backgroundColor: '#5856D6',
  },
  closeButton: {
    backgroundColor: '#007AFF',
  },
  buttonText: {
    fontSize: 16,
    fontWeight: '600',
    color: '#FFFFFF',
    marginLeft: 6,
  },
});

export default AutoVoiceGuide;
